<?php

namespace App\Tools;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class Helper
{
    /**
     * @param $path
     * @return mixed|string|null
     */
    public static function pathToUrl($path)
    {
        if (!$path) return $path;
        return Str::startsWith($path, 'http') ? $path : \Storage::url($path);
    }

    /**
     * @param $url
     * @return mixed|string|null
     */
    public static function urlToPath($url)
    {
        if (!$url) return $url;
        $disk = config('filesystems.default');
        $path = null;
        switch ($disk) {
            case 'public':
                //如果是前缀 去掉前缀则为路径
                $baseUrl = config('filesystems.disks.public.url');

                $path = Str::startsWith($url, $baseUrl) ? Str::replaceFirst($baseUrl, '', $url) : $url;

                break;

            default:
                abort(400, 'dist ' . $disk . ' dont have handler');
        }
        return $path;
    }

    public static function wrapOptions($options)
    {
        return collect($options)->map(function ($value, $key) {
            return [
                'key' => $key,
                'value' => $value,
            ];
        })->values();
    }

    /**
     * @param UploadedFile $file
     * @param $dir
     * @return string
     */
    public static function storeFile($file, $dir)
    {
        return $file->store($dir . '/' . date('Ymd'));
    }

    static function reduceSize($file_path, $max_width)
    {
        // 先实例化，传参是文件的磁盘物理路径
        $image = Image::make($file_path);
        // 进行大小调整的操作
        $image->resize($max_width, null, function ($constraint) {
            // 设定宽度是 $max_width，高度等比例双方缩放
            $constraint->aspectRatio();
            // 防止裁图时图片尺寸变大
            $constraint->upsize();
        });
        // 对图片修改后进行保存
        $image->save();
    }


    public static function formatPathAndUrl(string $path)
    {
        return [
            'path' => $path,
            'url' => self::pathToUrl($path),
        ];
    }

    public static function formatResponseData($data = [])
    {
        return response([
            'data' => $data,
            'message' => 'ok',
            'code' => 200
        ]);
    }

    public static function respErr($message, $code = 400, $data = [])
    {
        return response([
            'data' => $data,
            'message' => $message,
            'code' => $code
        ]);
    }

    public static function keysToString(array $arr, $split = ',')
    {
        return collect($arr)->keys()->join($split);
    }

    public static function getRandCode($length = 4)
    {
        if (app()->isLocal() && $length = 4) {
            $code = 1234;
        } else {
            $code = str_pad(rand(0, pow(10, $length) - 1), $length, 0, STR_PAD_LEFT);
        }
        return $code;
    }


    public static function getRandNumber($length = 12)
    {
        return substr(now()->format('YmdHis') . rand(100000, 999999), - $length);
    }


    static function arrTransformation(array $arr)
    {
        $tmpArr = [];
        foreach ($arr as $k => $v) {
            $tmpArr[] = [
                'value' => $v,
                'label' => $k
            ];
        }
        return $tmpArr;
    }

    static function yuanToCent($amountYuan)
    {
        return (int) ($amountYuan * 100);
    }

    static function hiddenPart($string, $leftLength = 1, $rightLength = 2)
    {
        if ($string) {
            return mb_substr($string, 0, $leftLength) . '****' . ($rightLength > 0 ? mb_substr($string, -$rightLength) : '');
        } else {
            return '******';
        }
    }

    static function interceptString($str,$start, $length)
    {
        $frontStr = mb_substr($str, $start, $length);
        $rearStr = mb_substr($str, $length);
        return [
            'front_str' => $frontStr,
            'rear_str' => $rearStr,
        ];
    }

    static function mbStrSplit ($string, $len) {
        $start = 0;
        $strlen = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string,$start,$len);
            $string = mb_substr($string, $len, $strlen);
            $strlen = mb_strlen($string);
        }
        return $array;
    }

    public static function formatSeconds($seconds)
    {
        $hours = str_pad(floor($seconds / 3600), 2, 0, STR_PAD_LEFT);
        $minutes = str_pad(floor(($seconds % 3600) / 60), 2, 0, STR_PAD_LEFT);
        $seconds = str_pad(floor($seconds % 60), 2, 0, STR_PAD_LEFT);

        return "$hours:$minutes:$seconds";
    }


    public static function secondsToHoursCN($seconds)
    {
        return self::minutesToHoursCN(ceil($seconds / 60));
    }

    public static function minutesToHoursCN($minutes)
    {
        if($minutes < 1) {
            return '-';
        }
        if($minutes < 60) {
            return $minutes . '分钟';
        }

        if($minutes % 30 == 0) {
            return round($minutes / 60, 1) . '小时';
        }

        return ($minutes >= 60 ? (floor($minutes / 60) . '小时') : '')
            . ($minutes % 60) . '分钟';
    }

}

